﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cqrs.Infrastructure.Aggregate;
using Cqrs.Infrastructure.Database;

// Taken directly from Greg Young's Simple.CQRS
namespace Cqrs.Infrastructure
{

    public interface IRepository<T> where T : AggregateRoot //, new()
    {
        void Save(AggregateRoot aggregate, int expectedVersion);
        T GetById(T aggregate, Guid id);
    }

    public class Repository<T> : IRepository<T> where T : AggregateRoot //, new() //shortcut you can do as you see fit with new()
    {
        private readonly IEventStore _storage;

        public Repository(IEventStore storage)
        {
            _storage = storage;
        }

        public virtual void Save(AggregateRoot aggregate, int expectedVersion)
        {
            _storage.SaveEvents(aggregate.Id, aggregate.GetUncommittedChanges(), expectedVersion, aggregate.GetType());
        }

        public virtual T GetById(T aggregate, Guid id)
        {
            var e = _storage.GetEventsForAggregate(id, null);
            aggregate.LoadsFromHistory(e);
            return aggregate;
        }
    }
}
